﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using Microsoft.Extensions.Configuration;
using Microsoft.Win32;
using ServoDrivesLib.Controls;
using ServoDrivesLibAbstract;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Forms.VisualStyles;
using System.Windows.Threading;
using 雷赛板卡上位机.Models;
using 雷赛板卡上位机.Services;
using 雷赛板卡上位机.Utilities;
using 雷赛板卡上位机.View;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using ServoDrivesLib.Model;

using ControlType = ServoDrivesLib.Model.ControlType;
namespace 雷赛板卡上位机.ViewModel
{
    public partial class MenuBarViewModel : BaseViewModel
    {
        int axisNums = 0; // 轴的数量
        readonly IControlCard? _controlCard; // 控制卡接口
        readonly IServoControl? _servo; // 伺服控制接口
        readonly IEtherCATMode? _etherCATMode; // EtherCAT 模式接口
        private readonly IConfiguration configuration;
        private readonly IPopUpService popUpService;
        private readonly string path;
        private readonly ControlType controlType;

        [ObservableProperty]
        ObservableCollection<MenuItem> _menuItems = new ObservableCollection<MenuItem>();
        public MenuBarViewModel(IConfiguration configuration, IPopUpService popUpService, CardControlManager cardControlManager) : base()
        {
            controlType = ControlService.GetControlType();
            this.configuration = configuration;
            this.popUpService = popUpService;
            _controlCard = cardControlManager.Get(controlType.ToString());
            _servo = _controlCard?.ServoControl;
            _etherCATMode = _controlCard?.EtherCATControl;
            base.IsActive = true;

            path = this.configuration.GetRequiredSection("LuaPath").Value;
            var dir = Directory.CreateDirectory(path);
            foreach (var item in dir.GetDirectories())
            {

                if (!item.Name.Equals("Base"))
                {
                    MenuItem menuItem = new MenuItem();
                    menuItem.Header = item.Name;
                    foreach (var fileInfo in item.GetFiles("*.lua"))
                    {
                        if (MenuItems.Count == 15) break;
                        if (!fileInfo.Name.Contains("Base"))
                            menuItem.Items.Add(new MenuItem() { Header = fileInfo.Name, Command = LoadLuaFilesCommand, CommandParameter = fileInfo.FullName });
                    }
                    MenuItems.Add(menuItem);

                }
            }
            foreach (var fileInfo in Directory.CreateDirectory(path).GetFiles("*.lua"))
            {
                if (MenuItems.Count == 15) break;
                if (!fileInfo.Name.Contains("Base"))
                    MenuItems.Add(new MenuItem() { Header = fileInfo.Name, Command = LoadLuaFilesCommand, CommandParameter = fileInfo.FullName });
            }

        }

        /// <summary>
        /// 连接板卡并初始化设备 
        /// </summary>
        [RelayCommand]
        void Connect()
        {
            if (CardControlInit(controlType))
            {
                _servo?.GetAxisNums(ref axisNums); // 获取轴的数量
                Messenger.Send<ValueChangedMessage<bool>, string>(new ValueChangedMessage<bool>(true), "AxisInit");
            }
        }
        /// <summary>
        /// 关闭板卡连接
        /// </summary>
        [RelayCommand]
        void Close()
        {
            ///需要添加垃圾回收
            Messenger.Send<ValueChangedMessage<bool>, string>(new ValueChangedMessage<bool>(true), "MenuClose");
            this._controlCard?.Close(); // 关闭控制卡
        }

        [RelayCommand]
        void LoadLuaFiles(object sender)
        {
            var path = sender as string;
            if (path != null)
            {
                string lua = File.ReadAllText(path);
                var inputTextBox = Messenger.Send<RequestMessage<InputTextBoxViewModel>>().Response;
                inputTextBox.Text = lua;
            }
        }

        [RelayCommand]

        void SelectLuaFile()
        {
            var retFile = OpenFileDialogEx.OpenFileDialog(".lua|*.lua");
            if (retFile == null)
            {
                MessageBox.Show("没有选择Lua文件", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            string lua = File.ReadAllText(retFile);
            var inputTextBox = Messenger.Send<RequestMessage<InputTextBoxViewModel>>().Response;
            inputTextBox.Text = lua;

        }
        /// <summary>
        /// 当视图模型激活时注册消息处理程序
        /// </summary>
        protected override void OnActivated()
        {
            Messenger?.Register<MenuBarViewModel, RequestMessage<int>, string>(this, "AxisNum",
                (r, m) =>
                {
                    m.Reply(this.axisNums); // 回复轴的数量
                    //m.Reply(10); // 回复固定的轴数量 
                });

            Messenger?.Register<MenuBarViewModel, RequestMessage<IServoControl?>, string>(this,
                "Servo",
                (r, m) => { m.Reply(r._servo); });

            Messenger?.Register<MenuBarViewModel, RequestMessage<IControlCard?>, string>(this,
                "Card",
                (r, m) => { m.Reply(r._controlCard); });
            Messenger?.Register<MenuBarViewModel, RequestMessage<IEtherCATMode?>, string>(this,
                "EtherCAT",
                (r, m) => { m.Reply(r._etherCATMode); });
            Messenger?.Register<MenuBarViewModel, RequestMessage<ControlType>>(this,
                (r, m) => { m.Reply(r.controlType); });
        }

        private bool CardControlInit(ControlType controlType)
        {
            bool value = false;
            switch (controlType)
            {
                case ControlType.Leisai:
                    var ret = this._controlCard?.Init(); // 初始化控制卡

                    if (ret <= 0) // 如果初始化失败，显示警告信息
                    {
                        MessageBox.Show($"未扫描到板卡,板块数{ret}", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);

                        break;
                    }
                    else
                    {
                        this._etherCATMode.ClearErrorCode();

                        #region 判断轴类型

                        _servo?.GetAxisNums(ref axisNums); // 获取轴的数量
                        if (axisNums > 0)
                        {
                            int typeNums = 0;
                            int count = 0;
                            for (int i = 0; i < axisNums; i++)
                            {
                                _servo?.GetAxisType(i, ref typeNums);
                                if (typeNums == 1)
                                {
                                    count++;
                                }
                            }
                            if (count == axisNums)
                            {
                                value = true;
                                break;
                            }
                            else
                            {
                                value = false;
                            }
                        }

                        #endregion

                        this._etherCATMode?.StartScan(); // 开始 EtherCAT 扫描
                        Thread.Sleep(100); // 等待 100 毫秒
                        this._etherCATMode?.EndScan(); // 结束 EtherCAT 扫描
                        this._etherCATMode?.SetCycleTime(1000);
                        this._controlCard?.DownloadMemFile(); // 下载内存文件
                        Thread.Sleep(100); // 等待 100 毫秒
                        this._controlCard?.Rest(CardResetStatus.Software); // 软件复位控制卡
                        this._controlCard?.Close(); // 关闭控制卡
                        //等待15秒
                        popUpService.ProgreeBar(15);


                        ret = this._controlCard?.Init(); // 再次初始化控制卡

                        if (ret <= 0) // 如果再次初始化失败，显示警告信息
                        {
                            MessageBox.Show($"未扫描到板卡,板块数{ret}", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                            break;
                        }
                    }
                    value = true;
                    break;
                case ControlType.ZMonition:
                    ret = this._controlCard?.Init(); // 初始化控制卡
                    popUpService.ProgreeBar(5);
                    value = true;
                    break;
                case ControlType.Soem:
                    MessageBox.Show("未实现请选择雷赛", "错误");
                    break;
            }
            return value;
        }
    }
}